package io.gitee.zhangbinhub.acp.boot.socket

import io.gitee.zhangbinhub.acp.boot.conf.AcpTcpServerConfiguration
import io.gitee.zhangbinhub.acp.boot.daemon.DaemonServiceManager
import io.gitee.zhangbinhub.acp.boot.init.BaseInitSocketServer
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.boot.socket.base.TcpServerHandle
import io.gitee.zhangbinhub.acp.boot.socket.tcp.TcpServer
import io.netty.handler.codec.ByteToMessageDecoder

/**
 * 初始化TCP服务
 */
class InitTcpServer(
    private val logAdapter: LogAdapter,
    private val acpTcpServerConfiguration: AcpTcpServerConfiguration,
    private val tcpServerHandle: MutableMap<String, TcpServerHandle>,
    private val byteToMessageDecoder: MutableMap<String, ByteToMessageDecoder>?
) : BaseInitSocketServer() {

    fun startTcpServer() {
        logAdapter.info("start tcp listen service ...")
        if (tcpServerHandle.isNotEmpty()) {
            tcpServerHandle.forEach { entity -> addServerHandle(entity.key, entity.value) }
        }
        if (!byteToMessageDecoder.isNullOrEmpty()) {
            byteToMessageDecoder.forEach { entity -> addMessageDecoder(entity.key, entity.value) }
        }
        try {
            val listens = acpTcpServerConfiguration.listeners
            if (listens.isNotEmpty()) {
                listens.forEach { listen ->
                    run {
                        if (listen.enabled) {
                            val beanName = listen.handleBean
                            getSocketServerHandle(beanName)?.let { handle ->
                                val port = listen.port
                                val tcpServer = TcpServer(
                                    logAdapter,
                                    port,
                                    listen,
                                    handle,
                                    getMessageDecoder(listen.messageDecoder)
                                )
                                val thread = Thread(tcpServer)
                                thread.isDaemon = true
                                thread.start()
                                DaemonServiceManager.addService(tcpServer)
                                logAdapter.info("start tcp listen service Success [" + listen.name + "] , port:" + listen.port)
                            } ?: logAdapter.error("tcp handle bean [$beanName] is invalid!")
                        } else {
                            logAdapter.info("tcp listen service is disabled [" + listen.name + "]")
                        }
                    }
                }
            } else {
                logAdapter.info("No tcp listen service was found")
            }
        } catch (e: Exception) {
            logAdapter.error(e.message, e)
        } finally {
            logAdapter.info("start tcp listen service finished!")
        }
    }

}
